package net.wantongtech.xa.uploadbasicinfo.service;

import com.wtkj.constant.NewClearingConstant;
import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wtkj.vo.dzzf.base.qxsjz.entity.MergeTransLog;
import com.wtkj.vo.dzzf.base.qxsjz.entity.PortalTransOut;
import com.wtkj.zwxt.stat.CardStaticValue;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.ProcessErrorMergeTransDao;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 处理错误的合并交易服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/19
 */
@Service
@Slf4j
public class ProcessErrorMergeTransService {

    @Resource
    private ProcessErrorMergeTransDao processErrorMergeTransDao;

    public void process() {
        List<MergeTransLog> mergeLogList = processErrorMergeTransDao.queryMergeTransLogInfo();
        log.info("共查询出{}条待处理的合并日志数据", mergeLogList.size());
        if (mergeLogList.isEmpty()) {
            return;
        }
        mergeLogList.forEach(mergeTransLog -> {
            try {
                processSingle(mergeTransLog);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });
    }


    private void processSingle(MergeTransLog mergeTransLog) {
        String passId = mergeTransLog.getPassId();
        log.info("待处理passId为：{}", passId);
        List<PortalTransOut> portalTransOutList = processErrorMergeTransDao.queryPortalTransOutByPassId(passId);
        log.info("共查询出{}条对应的原始交易数据", portalTransOutList.size());
        portalTransOutList.forEach(portalTransOut -> {

            Integer etcCardType = portalTransOut.getEtcCardType();
            String issuerId = portalTransOut.getIssuerId();

            if (!NewClearingConstant.JT_ISSUER_ID.equals(issuerId)) {
                return;
            }

            if (StringUtils.isBlank(portalTransOut.getSignSource())) {
                return;
            }

            if (etcCardType != CardStaticValue.CardType.CZK_Card) {
                return;
            }

            String etcCardId = portalTransOut.getEtcCardId();

            if (StringUtils.length(etcCardId) != 20) {
                return;
            }

            if (!"22".equals(StringUtils.substring(etcCardId, 8, 10))) {
                return;
            }

            String eCardNo = etcCardId.substring(4);
            CardInfo cardInfo = processErrorMergeTransDao.queryCardInfoByCardNo(eCardNo);
            if (cardInfo == null || cardInfo.getECardType() != CardStaticValue.CardType.CZK_Card
                    || cardInfo.getCardNetID() != 6101) {
                return;
            }

            String transactionId = portalTransOut.getTransactionId();
            log.info("passId：{}，transactionId：{}，etcCardId：{}，对应signSource值错误", passId,
                    transactionId, etcCardId);

            processErrorMergeTransDao.updateSignSourceToNull(transactionId);

        });
    }
}
